package com.tansun.easycare.rule.ruleproj.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.jeedev.msdp.sys.entity.SysRole;
import com.tansun.easycare.core.service.impl.CrudServiceImpl;
import com.tansun.easycare.modules.sys.service.RoleService;
import com.tansun.easycare.modules.sys.utils.UserUtils;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.exception.DataEmptyException;
import com.tansun.easycare.rule.exception.DataExistException;
import com.tansun.easycare.rule.ruleproj.dao.RuleProjectDao;
import com.tansun.easycare.rule.ruleproj.dao.RuleProjectReferenceDao;
import com.tansun.easycare.rule.ruleproj.entity.RuleAuthority;
import com.tansun.easycare.rule.ruleproj.entity.RuleProjEntity;
import com.tansun.easycare.rule.ruleproj.entity.RuleProject;
import com.tansun.easycare.rule.ruleproj.entity.RuleProjectRank;
import com.tansun.easycare.rule.ruleproj.model.RuleprojectVO;
import com.tansun.easycare.rule.ruleproj.service.RuleAuthorityService;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectRankService;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectService;

/**
 * 规则项目管理ServiceImpl
 * @author lph
 * @version 2017-02-06
 */
@Service("ruleProjectService")
@Transactional(readOnly = true)
public class RuleProjectServiceImpl extends CrudServiceImpl<RuleProjectDao, RuleProject> implements RuleProjectService{
	@Autowired
	private RuleAuthorityService ruleAuthorityService;
	@Autowired
	private RuleProjectRankService ruleProjectRankService;
	@Autowired
	private RuleProjectReferenceDao ruleReferenceDao;
	@Autowired 
	private RoleService roleService;
	
//	@Autowired
//	private UserDao userDao;
	
	@Transactional(readOnly = false)
	public void saveOrUpdate(RuleProjEntity ruleProjEntity){
		RuleProject rp = ruleProjEntity.getRuleProject();
		if(StringUtils.isEmpty(rp.getProjectname())){
			throw new DataEmptyException("请输入规则项目名称");
		}
		if(StringUtils.isEmpty(rp.getProjectcode())){
			throw new DataEmptyException("请输入规则编码名称");
		}
		String msg = isExist(rp);
		if(msg.length()>0){
			throw new DataExistException(msg);
		}
		rp.setStatus("1");
		this.save(rp);
		ruleAuthorityService.deleteByCode(ruleProjEntity.getRuleProject().getProjectcode());
//		for(RuleAuthority item : ruleProjEntity.getRuleUserAuthList()){
//			item.setId(IdGen.uuid());
//		}
		ruleAuthorityService.insertBatch(ruleProjEntity.getRuleUserAuthList());
        RuleProjectRank rankCondition = new RuleProjectRank();
        rankCondition.setProjectCode(rp.getProjectcode());
        List<RuleProjectRank> ranklist = ruleProjectRankService.findList(rankCondition);
        if(ranklist!=null) {
            for (RuleProjectRank ruleProjectRank : ranklist) {
    			if(rp.getProjectcode().equals(ruleProjectRank.getNodeId()) && !ruleProjectRank.getName().equals(rp.getProjectname())) {
    				ruleProjectRank.setName(rp.getProjectname());
    				ruleProjectRankService.save(ruleProjectRank);
    				break;
    			}
    		}
        }
		ruleProjectRankService.initBaseModule(rp.getProjectname(), rp.getProjectcode(),false,ranklist);
		DataCache.ruleProjectChange(rp.getProjectcode());
		DataCache.ruleAuthorityChange();
	}
	/**
	 * 获取当前用户具有权限的项目
	 * @param projectCode
	 * @return
	 */
	public List<RuleProject> getUserRuleAuthProj(String projectCode,RuleAuthority currAuth){
		String userName = UserUtils.getSysService().getCurrUser().getLoginName(); 
//		String userName ="administrator";
		List<RuleProject> ruleList = this.findAllList();
		if("administrator".equals(userName)){
			return ruleList;
		}else{
			//获取当前用户所具有权限的规则项目
			List<RuleProject> resultList = new ArrayList<RuleProject>();
			Map<String,List<RuleAuthority>> raListMap = this.findRuleAuthorityMap();
			for (RuleProject ruleProject : ruleList) {
				List<RuleAuthority> authList= raListMap.get(ruleProject.getProjectcode());
				for (RuleAuthority userAuthority : authList) {
					if(userAuthority.getUsercode().equals(userName)){
						if(ruleProject.getProjectcode().equals(projectCode)){
							currAuth = userAuthority;
						}
						resultList.add(ruleProject);
					}
				}	
			}
			return resultList;
		}
	}
	
	/**
	 * 获取权限 map形式 key为projectCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String,List<RuleAuthority>> findRuleAuthorityMap(){
		Map<String,List<RuleAuthority>> raListMap = null;
		String cacheKey = DataCache.getCacheKey(null, DataCache.RULE_AUTH_MAP_OPTION);
//		if( DataCache.canGetFromCache(cacheKey) ) {
//			raListMap = (Map<String,List<RuleAuthority>>)DataCache.getValue(cacheKey);
//		}else {
			RuleAuthority condition = new RuleAuthority();
			List<RuleAuthority> authAllList = ruleAuthorityService.findList(condition);
			raListMap = new HashMap<String,List<RuleAuthority>>();
			for (RuleAuthority userAuthority : authAllList) {
				String key = userAuthority.getProjectcode();
				List<RuleAuthority> aList = null;
				if( raListMap.containsKey(key)) {
					aList = raListMap.get(key);
				}else {
					aList = new ArrayList<RuleAuthority>();
					raListMap.put(key, aList);
				}
				aList.add(userAuthority);
			}
			DataCache.setValue(cacheKey, raListMap);
//		}
		return raListMap;
	}
	/**
	 * 获取当前角色具有权限的项目  HX 20191128
	 * @param projectCode
	 * @return
	 */
	public List<RuleProject> getRoleRuleAuthProj(String projectCode,RuleAuthority currAuth){
		List<SysRole> roles = roleService.findRolesByUserNum(UserUtils.getSysService().getCurrUser().getUserNum());
//		SysUser user =UserUtils.getSysService().getCurrUser();
//		System.out.print(user);
		String rolesString = "";
		for(SysRole role:roles){
			rolesString = rolesString + role.getRoleCode();
		}
		List<RuleProject> ruleList = this.findAllList();
		//获取当前用户所具有权限的规则项目
		List<RuleProject> resultList = new ArrayList<RuleProject>();
		Map<String,List<RuleAuthority>> raListMap = this.findRuleAuthorityMap();
		for (RuleProject ruleProject : ruleList) {
			List<RuleAuthority> authList= raListMap.get(ruleProject.getProjectcode());
			if(authList!=null) {
				for (RuleAuthority userAuthority : authList) {
					if(rolesString!=null && userAuthority.getRolecode()!=null && rolesString.indexOf(userAuthority.getRolecode())>-1){
						resultList.add(ruleProject);
						break;
					}
				}
			}
		}
		return resultList;
	}
	/**
	 * 根据规则项目编号获取当前用户的规则模块操作权限
	 * @param projectCode
	 * @return
	 */
	public List<RuleAuthority> getProjAuthInfo(String projectCode,String usercode){
		/*if(StringUtils.isEmpty(usercode)){
			usercode = UserUtils.getUser().getLoginName();
		}*/
		Map<String,List<RuleAuthority>> raListMap = this.findRuleAuthorityMap();
		List<RuleAuthority> resLists = raListMap.get(projectCode);
		List<RuleAuthority> authList = null;
		if(StringUtils.isEmpty(usercode)){
			authList = resLists;
		}else {
			authList = new ArrayList<RuleAuthority>();
			for(RuleAuthority auth:resLists) {
				if(auth.getUsercode().equals(usercode)) {
					authList.add(auth);
				}
			}
		}
		if(authList.size()==0)
			throw new DataEmptyException("未找到对应的规则项目权限");
		return authList;
	}
	/**
	 * 根据规则项目编号获取当前用户的规则模块操作权限 HX 20191128
	 * @return
	 */
	public List<RuleAuthority> getProjAuthInfoByRoleCode(String projectCode,List<SysRole> roles){
		RuleAuthority condition = new RuleAuthority();
		condition.setProjectcode(projectCode);
		if(roles.size()<1){
			roles = roleService.findRolesByUserNum(UserUtils.getSysService().getCurrUser().getUserNum());
		}
		Map<String,List<RuleAuthority>> raListMap = this.findRuleAuthorityMap();
		List<RuleAuthority> resLists = raListMap.get(projectCode);
		
		List<RuleAuthority> authLists = new ArrayList<RuleAuthority>();
		if( resLists!=null && resLists.size() > 0) {
			for(SysRole role:roles){
				for(RuleAuthority auth:resLists) {
					if("true".equals(auth.getIsrole()) && auth.getRolecode().equals(role.getRoleCode()) && !authLists.contains(auth)) {
						authLists.add(auth);
					}
				}
			}
		}
		if(authLists.size()==0)
			throw new DataEmptyException("未找到对应的规则项目权限。");
		return authLists;
	}
	public RuleProject get(String id) {
		return super.get(id);
	}
	public RuleProject getByCode(String projectCode) {
		return this.dao.getByCode(projectCode);
	}
	@SuppressWarnings("unchecked")
	public List<RuleProject> findAllList() {
		List<RuleProject> pojList = null;
		String cacheKey = DataCache.getCacheKey(null, DataCache.RULE_PRO_LIST_OPTION);
		if( DataCache.canGetFromCache(cacheKey) ) {
			pojList = (List<RuleProject>)DataCache.getValue(cacheKey);
		}else {
			pojList = super.findList(null);
			DataCache.setValue(cacheKey, pojList);
		}
		return pojList;
	}
	
	public List<RuleProject> findList(RuleProject ruleProject) {
		return super.findList(ruleProject);
	}
	public PageInfo<RuleProject> findPage(Page<RuleProject> page, RuleProject ruleProject) {
		return super.findPage(page, ruleProject);
	}
	@Transactional(readOnly = false)
	public void save(RuleProject ruleProject) {
		super.save(ruleProject);
		DataCache.ruleProjectChange(ruleProject.getProjectcode());
		DataCache.ruleAuthorityChange();
	}
	/**
	 * 删除规则项目信息,需要对应删除规则项目对应的用户操作权限信息
	 */
	@Transactional(readOnly = false)
	public void delete(RuleProject ruleProject) {
		super.delete(ruleProject);
		//还需要删除规则项目对应的权限信息
		ruleAuthorityService.deleteByCode(ruleProject.getProjectcode());
		DataCache.ruleProjectChange(ruleProject.getProjectcode());
		DataCache.ruleAuthorityChange();
	}
	
	/**
	 * 根据条件判断是否存在重复
	 * @param projectName
	 * @param type name || code
	 * @return
	 */
	@Override
	public  String isExist(RuleProject rp){
		RuleProject condition = new RuleProject();
		condition.setId(rp.getId());
		condition.setProjectname(rp.getProjectname());
		condition.setStatus("1");
		int count = this.dao.ruleProjExistCount(condition);
		if(count>0){
			return "规则项目名称重复，请重新填写";
		}
		condition.setProjectname("");
		condition.setProjectcode(rp.getProjectcode());
		count = this.dao.ruleProjExistCount(condition);
		if(count>0){
			return "规则项目编码重复，请重新填写";
		}
		return "";
	}
	@Override
	public PageInfo<RuleprojectVO> findPageRef(Page<RuleprojectVO> page, RuleprojectVO ruleProjectVO) {
		if(!ruleProjectVO.getCreateBy().isEmpty() && ruleProjectVO.getCreateBy()!="") {
			String creId = UserUtils.getSysService().getByRealName(ruleProjectVO.getCreateBy()).getId();
			if(creId!="" && creId!=null) {
				ruleProjectVO.setCreateBy(creId);
			}
		}
		if(!ruleProjectVO.getUpdateBy().isEmpty() && ruleProjectVO.getUpdateBy()!="") {
			String updId = UserUtils.getSysService().getByRealName(ruleProjectVO.getUpdateBy()).getId();
			if(updId!="" && updId!=null) {
				ruleProjectVO.setUpdateBy(updId);
			}
		}
		PageInfo<RuleprojectVO> resPage = new PageInfo<>(this.dao.findRuleProjectVO(ruleProjectVO));
//		PageInfo<RuleprojectVO> resPage = super.findPage(ruleProjectVO.getPage(), ruleProjectVO);
		return resPage;
	}
	@Override
	public List<RuleProject> getByCodeListForRef(List<String> list){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("list", list);
		return this.dao.getByCodeListForRef(map);
    }
	PageInfo<RuleProject> toRefPage(PageInfo<RuleProject> beforePage){
		List<RuleProject> list = beforePage.getList();
		if(list!=null && list.size()>0){
			for(RuleProject ruleProject : list){
				String projectcode = ruleProject.getProjectcode();
				List<String> refProNameList = ruleReferenceDao.getRefProName(projectcode);
				ruleProject.setRefs(refProNameList);
			}
		}
		return  beforePage;
	}
	public RuleProject getByCodeForRef(String getByCodeForRef) {
		//return this.dao.getByCodeForRef(getByCodeForRef);
		return null;
	}
}